<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备id" prop="sensorId">
        <el-input
          v-model="queryParams.sensorId"
          placeholder="请输入设备id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

<!--      &lt;!&ndash; 新增网页链接查询 &ndash;&gt;-->
<!--      <el-form-item label="网页链接" prop="linkUrl">-->
<!--        <el-input-->
<!--          v-model="queryParams.linkUrl"-->
<!--          placeholder="请输入网页链接"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleLinkQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="el-icon-link" size="mini" @click="handleLinkQuery">查询链接</el-button>-->
<!--      </el-form-item>-->

    </el-form>


    <el-row :gutter="10" class="mb8">
      <!-- 在工具栏加一个按钮 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-link"
          size="mini"
          @click="openApiDialog"
        >设备查询</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['sensor:sensor:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['sensor:sensor:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['sensor:sensor:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['sensor:sensor:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="设备id" align="center" prop="sensorId" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="记录数" align="center" prop="recordsNum" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['sensor:sensor:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['sensor:sensor:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备id" prop="sensorId">
          <el-input v-model="form.sensorId" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="设备imei号" prop="sensorImei">
          <el-input v-model="form.sensorImei" placeholder="请输入设备imei号" />
        </el-form-item>
        <el-form-item label="记录数" prop="recordsNum">
          <el-input v-model="form.recordsNum" placeholder="请输入记录数" />
        </el-form-item>
        <el-form-item label="创建者" prop="createUser">
          <el-input v-model="form.createUser" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="更新者" prop="updateUser">
          <el-input v-model="form.updateUser" placeholder="请输入更新者" />
        </el-form-item>
        <el-form-item label="${comment}" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入${comment}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增引导查询弹框 -->
    <el-dialog :title="'接口查询'" :visible.sync="apiDialogOpen" width="600px" append-to-body>
      <el-form :model="apiForm" ref="apiForm" label-width="100px">
        <!-- 服务器地址 -->
        <el-form-item label="服务器地址" prop="server">
          <el-input v-model="apiForm.server" placeholder="请输入服务器地址" />
        </el-form-item>

        <!-- 查询类型 -->
        <el-form-item label="查询类型" prop="type">
          <el-select v-model="apiForm.type" placeholder="请选择查询类型" style="width: 100%">
            <el-option label="设备列表" value="devices" />
            <el-option label="记录数" value="recordsNum" />
            <el-option label="数据记录详情" value="recordDetail" />
          </el-select>
        </el-form-item>

        <!-- 如果是记录数 / 数据记录详情，显示设备ID输入 -->
        <el-form-item v-if="apiForm.type === 'recordsNum' || apiForm.type === 'recordDetail'" label="设备ID" prop="dev">
          <el-input v-model="apiForm.dev" placeholder="请输入设备ID" />
        </el-form-item>

        <!-- 如果是数据记录详情，显示索引输入 -->
        <el-form-item v-if="apiForm.type === 'recordDetail'" label="索引" prop="index">
          <el-input v-model="apiForm.index" placeholder="请输入索引号" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="apiDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitApiQuery">确 定</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listSensor, getSensor, delSensor, addSensor, updateSensor ,queryDeviceApi} from "@/api/sensor/sensor";

export default {
  name: "Sensor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      sensorList: [],
      // 新增：引导查询弹框
      apiDialogOpen: false,
      apiForm: {
        server: "121.41.104.250:57346", // 默认服务器地址
        type: null,   // 查询类型
        dev: null,    // 设备ID
        index: null   // 索引
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sensorId: null,
        status: null,
        linkUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    // 打开弹框
    openApiDialog() {
      this.apiDialogOpen = true;
      this.apiForm = { server: "121.41.104.250:57346", type: null, dev: null, index: null };
    },

    // 提交接口查询
    submitApiQuery() {
      if (!this.apiForm.type) {
        this.$message.warning("请选择查询类型");
        return;
      }
      // 调用后端接口
      queryDeviceApi(this.apiForm).then(res => {
        if (res.code === 200) {
          this.$message.success("查询成功");
          console.log("查询结果:", res.data);

          // 如果后端返回列表，可以直接绑定到表格
          if (Array.isArray(res.data)) {
            this.sensorList = res.data.map((id, idx) => ({ id: idx + 1, sensorId: id }));
          }
        } else {
          this.$message.error("查询失败：" + res.msg);
        }
      }).catch(err => {
        // 网络异常等
        this.$message.error("请求异常：" + err);
      });

      this.apiDialogOpen = false;
    },


    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listSensor(this.queryParams).then(response => {
        this.sensorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sensorId: null,
        sensorImei: null,
        status: null,
        recordsNum: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 网页链接查询 */
    handleLinkQuery() {
      if (!this.queryParams.linkUrl) {
        this.$message.warning("请输入网页链接");
        return;
      }
      checkLink({ url: this.queryParams.linkUrl }).then(response => {
        console.log("后端返回:", response);
        this.$message.success("网页链接查询完成");
        // 这里可以把返回结果绑定到表格
        this.sensorList = response.rows || [];
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSensor(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + ids + '"的数据项？').then(function() {
        return delSensor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sensor/sensor/export', {
        ...this.queryParams
      }, `sensor_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
